package com.feonix.common.permission;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.feonix.common.util.StringUtil;

public class PermissionAdapterHander {
	private static final Log logger = LogFactory.getLog(PermissionAdapterHander.class);

	private static Map<String, AbsPermissionAdapter> permissionAdapterMap = new HashMap<String, AbsPermissionAdapter>();
	public static final String DEFAULT_PERMISSIONADAPTER_KEY = "default";

	/**
	 * 新增权限适配器
	 * 
	 * @param key
	 * @param className
	 */
	public static void add(String key, String className) {
		if ((!(StringUtil.isNotEmpty(key))) || (!(StringUtil.isNotEmpty(className))))
			return;
		try {
			Class<?> clazz = Class.forName(className);
			AbsPermissionAdapter permissionAdapter = (AbsPermissionAdapter) clazz.newInstance();
			permissionAdapterMap.put(key, permissionAdapter);
		} catch (Exception exception) {
			logger.error("add error", exception);
		}
	}

	/**
	 * 设置一个适配器的验证模式
	 * 
	 * @param key
	 * @param validModal
	 */
	public static void setValidModal(String key, ValidModal validModal) {
		AbsPermissionAdapter permissionAdapter = getAdapter(key);
		if ((permissionAdapter != null) && (validModal != null))
			permissionAdapter.setValidModal(validModal);
	}

	/**
	 * 新增权限适配器
	 * 
	 * @param key
	 * @param permissionAdapter
	 */
	public static void add(String key, AbsPermissionAdapter permissionAdapter) {
		if ((StringUtil.isNotEmpty(key)) && (permissionAdapter != null))
			permissionAdapterMap.put(key, permissionAdapter);
	}

	/**
	 * 获得默认权限适配器
	 * 
	 * @return
	 */
	public static AbsPermissionAdapter getDefault() {
		return getAdapter("default");
	}

	/**
	 * 获得权限适配器
	 * 
	 * @param paramString
	 * @return
	 */
	public static AbsPermissionAdapter getAdapter(String key) {
		return permissionAdapterMap.get(key);
	}

	/**
	 * 获得权限适配器，如果key指向的获取不到，就拿default
	 * 
	 * @param paramString
	 * @return
	 */
	public static AbsPermissionAdapter getAdapterWithDefault(String key) {
		AbsPermissionAdapter permissionAdapter = getAdapter(key);
		if (permissionAdapter == null) {
			permissionAdapter = getDefault();
		}
		return permissionAdapter;
	}
}
